import React, { useState } from 'react'
import { Form, Input, Button, Card, message, Typography } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { useRouter } from 'next/router'
import { authAPI } from '../utils/api'

const { Title } = Typography

export default function Login() {
  const [loading, setLoading] = useState(false)
  const router = useRouter()

  const onFinish = async (values: any) => {
    console.log('Login form submitted:', values)
    setLoading(true)
    
    try {
      // 调用真实的登录API
      const response = await authAPI.login({
        email: values.username, // 使用email字段
        password: values.password
      })
      
      if (response.data.token && response.data.user) {
        // 存储到 localStorage
        if (typeof window !== 'undefined') {
          localStorage.setItem('token', response.data.token)
          localStorage.setItem('user', JSON.stringify(response.data.user))
        }
        
        message.success('登录成功！正在跳转...')
        
        // 跳转到仪表板
        setTimeout(() => {
          router.push('/dashboard')
        }, 1000)
      } else {
        message.error('登录响应格式错误')
      }
    } catch (error: any) {
      console.error('Login error:', error)
      if (error.response?.data?.error) {
        message.error(error.response.data.error)
      } else if (error.message.includes('Network Error')) {
        message.error('网络连接失败，请检查后端服务是否运行')
      } else {
        message.error('登录失败，请稍后重试')
      }
    } finally {
      setLoading(false)
    }
  }

  return (
    <div style={{
      minHeight: '100vh',
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
    }}>
      <Card style={{ width: 400, boxShadow: '0 4px 12px rgba(0,0,0,0.15)' }}>
        <div style={{ textAlign: 'center', marginBottom: 24 }}>
          <Title level={2} style={{ color: '#1890ff', marginBottom: 8 }}>
            智慧园区
          </Title>
          <p style={{ color: '#666', margin: 0 }}>管理系统登录</p>
        </div>
        
        <Form
          name="login"
          onFinish={onFinish}
          autoComplete="off"
          size="large"
        >
          <Form.Item
            name="username"
            rules={[
              { required: true, message: '请输入邮箱!' },
              { type: 'email', message: '请输入有效的邮箱地址!' }
            ]}
          >
            <Input 
              prefix={<UserOutlined />} 
              placeholder="邮箱" 
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
            />
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={loading}
              style={{ width: '100%' }}
            >
              登录
            </Button>
          </Form.Item>
        </Form>
        
        <div style={{ textAlign: 'center', marginTop: 16, color: '#666', fontSize: '12px' }}>
          <p>测试账号：admin@example.com</p>
          <p>测试密码：admin123</p>
        </div>
      </Card>
    </div>
  )
}
